package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import myJDBC.myConnection;
import myJDBC.lowLevel.AuthChecker;
import ejb.IRemoteAuthValidator;
import ejb.IRemoteLoginnedUserBean;

@WebServlet("/Auth")
public class Auth extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {
		  if (!(myConnection.dbConnection == null)) {
		     if(myConnection.dbConnection.isClosed()){
				  myConnection.Connect();
				}
		  } else {
			 myConnection.Connect();
		  }
		} catch (ClassNotFoundException |SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean valid = false;
		String type = request.getParameter("type");
		if (type.equals("login")) {
			Random random = new Random(System.nanoTime());
			String log = request.getParameter("login");
			String pass = request.getParameter("pass");
			ArrayList<Integer> groupids=new ArrayList<Integer>();
			ArrayList<String> groupnames=new ArrayList<String>();
			Integer objId = 0;
			try {
				ArrayList<String> tmp = AuthChecker.Check(log, pass);
				if (tmp.size() != 0) {
					objId = Integer.parseInt(tmp.get(0));
					for(int i=1;i<tmp.indexOf(null); i++)
						groupids.add(Integer.parseInt(tmp.get(i)));
					for(int i=tmp.indexOf(null)+1;i<tmp.size(); i++)
						groupnames.add((tmp.get(i)));
					valid = true;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (valid) {
				// int object_id = 20;
				// int role_id = 11; //
				int token = log.hashCode() + random.nextInt(1000000000);

				// создаю бин юзера и засовываю в сессию
				Properties props = new Properties();
				Context context;
				try {
					props.put(Context.INITIAL_CONTEXT_FACTORY,
							"org.jboss.naming.remote.client.InitialContextFactory");
					props.put(Context.PROVIDER_URL, "remote://localhost:4447");
					context = new InitialContext(props);
					IRemoteLoginnedUserBean bean = (IRemoteLoginnedUserBean) context
							.lookup("/netcracker/LoginnedUserBean!ejb.IRemoteLoginnedUserBean");
					bean.fillFields(log, objId, groupids,groupnames, token);
					HttpSession s = request.getSession();
					s.setAttribute("userBean", bean);

					// в синглтон добавляю нового
					IRemoteAuthValidator bean2 = (IRemoteAuthValidator) context.lookup("/netcracker/AuthValidator!ejb.IRemoteAuthValidator");
					bean2.newAuthorisation(log, token,
							System.currentTimeMillis());

				} catch (Exception e) {
					e.printStackTrace();
				}
				response.sendRedirect("privateOffice");
				// request.getRequestDispatcher("mainMenu").forward(request,
				// response);
			} else {
				response.sendRedirect("login");
			}
		} else if (type.equals("logout")) {
			// logout
			// как удалить бин??

			// IRemoteLoginnedUserBean bean=(IRemoteLoginnedUserBean)
			// request.getSession().getAttribute("userBean");
			((IRemoteLoginnedUserBean) request.getSession().getAttribute("userBean")).removeBean();
			request.getSession().removeAttribute("userBean");
			response.sendRedirect("login");
			// request.getRequestDispatcher("login").forward(request,
			// response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
